#
# Common reporting subroutines for the Linux Counter
# It should be a module; I will learn how to do it when I
# understand Export....
#
package Reportsub;
require Exporter;
use Counter;
use strict;

use vars qw(@ISA @EXPORT
  %longname %usercount %population %hostcount
  %statename %hasstates
  $statesloaded
	     );


@ISA = qw(Exporter);

  # line 1: routines
  # line 2-3: variables - this is bad modularity
@EXPORT = qw(
  readfile printwithcommas getcountryinfo loadstates keycase
  %longname %usercount %population %hostcount
  %statename %hasstates
	     );
             

sub readfile {
    my($file, $fields, $sums) = @_;
    my $field;
    open(PERS, $file) || die "Unable to open $file\n";
    while (<PERS>) {
	chop;
	if (/^\/\/.*:(\S+)$/) {
	    $field = $1;
	} elsif (/^"(.*)":(\d+)$/) {
	    $$fields{$field}{$1} = $2;
	} elsif (/^(\S+):(\d+)$/) {
	    $$sums{$field}{$1} = $2;
	} else {
	    print STDERR "Unparsed line: $_\n";
	}
    }
}

sub printwithcommas {
    my $number = shift;
    my $string;

    while ($number > 1000) {
	$string = sprintf(",%03d", $number % 1000) . $string;
	$number /= 1000;
    }
    $string = sprintf("%d", $number) . $string;
    $string;
}

sub getcountryinfo {
    my $places = Counter::openfile("places");
   
    my @countries = $places->selectany("name, longname, population, users, hostcount
         from places where type = 'country'");
    for my $place (@countries) {
	my $c = $$place{name};
	die "Nameless" if !$c;
	$usercount{$c} = $$place{users};
	$longname{$c} = $$place{longname};
	$population{$c} = $$place{population};
	$hostcount{$c} = $$place{hostcount};
    }
}


sub loadstates {
   return if $statesloaded;
   my($country, $state, $longname, $states);
   open(STATES, "data/statenames") || die "Unable to open statenames\n";
   while (<STATES>) {
      chop;
      next if /^#/;
      my ($country, $state, $longname) = split(/\t/);
      if (!$longname && $state) {
          $longname = $state;
      }
      $longname =~ s/\s+$//;
      $country =~ tr/a-z/A-Z/;
      $statename{$country, $state} = $longname;
      ++ $hasstates{$country};
      ++ $states;
   }
   print STDERR "$states states loaded\n";
   $statesloaded = 1;
}

# Used for cleaning city names to make keys out of them:
# Map the non-ASCII parts of 8859-1 to ASCII, upcase first
# Seems nobody uses this...
#sub keycase {
#    my $val = shift;
#
#    $val =~ tr/\300-\337/AAAAAAACEEEEIIIIDNOOOOOxOUUUUYTs/;
#    $val =~ tr/\340-\377/aaaaaaaceeeeiiiidnoooooxouuuuyty/;
#    $val = "\L\u$val";   # black magic....lowercase all, upcase first
#    $val;
#}


1;
